03. Inheritance

Inheritance

ND079 C1 L3 A03 Inheritance

Inheritance

Inheritance is one class acquiring properties and methods from another class. Here are some key points you should remember about inheritance:

  • We want to go from general to specific. The parent or superclass is the most general and the child or subclass is the more specific.
  • By extending the superclass you are stating that the subclass is of the superclass type. When we're not sure if a subclass is inheriting from a parent class, we can use the “is a” test (e.g. a car is a vehicle).
  • The relationship between superclass and subclasses is only one way. The subclasses need to know about the superclass, but the superclass should never know anything about its subclasses.

The Object Superclass

Every class inherits from the superclass Object. Because all objects inherit from the Object class, there are some methods that all objects have, no matter what types they are. For example, all objects have:

  • clone(), so that we can clone or make a copy of any object.
  • equals(), which we can use to determine if two objects are the same.
  • hashCode(), which provides a unique hash code for each object. This is something we'll make use of later on when we need to store and retrieve objects in specific data sets.
  • toString(), which we can use to get a description of the current state of an object.

Why do we use inheritance?

(Select all that apply.)

SOLUTION:
  • To promote code reusability and reduce duplicate code.
  • To create relationships between classes, going from general to specific.
  • To share state and/or behavior with other related classes.

Vehicle Example in Code

Now that we have discussed the general concept of inheritance, let's take a look at how the vehicle example might be implemented in actual code. You aren't expected to write this code yourself—this is just an example. We will go through an exercise shortly in which you will get the opportunity to make use of inheritance.

ND079 C1 L3 A04 Inheritance Demo